import {
    EditOutlined,
    SearchOutlined,
    SyncOutlined,
    PlusOutlined,
    DeleteOutlined,
    SaveOutlined,
    CloseOutlined
} from '@ant-design/icons'
import '../index.css'
import { Button, Form, Input, Table, Card, message, Tag, Popconfirm, Drawer } from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import React, { useState, useEffect } from 'react'
import TableToolbar from '../../../../components/TableSetting/TableToolbar'
import { fetchRequest } from '../../../../utils/Request'
import { url } from '../../../../utils/url'
import { useDispatch, useSelector } from 'react-redux'
import actionType from './addressActionType'
import { useRequest } from '@umijs/hooks'
import AddAddress from "./AddAddress";
import { string } from "prop-types";
import AddCampus from "./AddCampus";


const EditableCell: React.FC<any> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {




    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{ margin: 0 }}
                    rules={[
                        {
                            required: true,
                            message: `请输入${title}!`,
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

export default function AddressManageTable() {

    interface requestParams {
        index: number,
        num: number,
        collegeAreaId: string,
        building: string,
        unit: string
    }

    const addressInfo = useSelector((state: any) => {
        return state.addressManage;
    })

    const Info = useSelector((state: any) => {
        return state.entranceManage;
    })
    const [editingKey, setEditingKey] = useState('');

    const [columnsKey, setcolumnsKey] = useState<any[]>([])
    const [realColumns, setrealColumns] = useState<any[]>([])
    const [addVisible, setaddVisible] = useState<boolean>(false)
    const dispatch = useDispatch()

    const [form] = Form.useForm()


    const isEditing = (record: any) => record.collegeAreaId === editingKey;
    const cancel = () => {
        setEditingKey('');
    };

    const edit = (record: any) => {
        form.setFieldsValue({ ...record });
        setEditingKey(record.collegeAreaId);
    }

    const save = async (key: any) => {
        try {
            const row = await form.validateFields();
            const newData = [...addressInfo.campustable.data];


            const index = newData.findIndex(item => key === item.collegeAreaId);

            if (index > -1) {
                const item = newData[index];

                const { success, error } = await run({
                    ...row,
                    collegeAreaId: item.collegeAreaId,
                    collegeId: item.collegeId
                })

                if (success) {
                    newData.splice(index, 1, {
                        ...item,
                        ...row,
                    });

                    dispatch({
                        type: actionType.GET_CAMPUS_TABLE,
                        payload: { ...addressInfo.campustable, data: newData, }
                    })

                    setEditingKey('');
                } else {
                    message.error(error)
                }


            }

        } catch (e) {

        }
    }


    const { run } = useRequest((params) => fetchRequest(url.EDIT_collegeArea, params), {
        manual: true,
    })

    const columns = [{
        title: '学校',
        dataIndex: 'collegeName',
        key: 'collegeName'
    }, {
        title: '校区',
        dataIndex: 'collegeAreaName',
        key: 'collegeAreaName',
        editable: true,
    }
        , {
        title: "操作", render: (_: any, record: any) => {

            const editable = isEditing(record);

            return editable ? (<>
                <Tag className="tags-hover " color="#f50" icon={<SaveOutlined />}
                    onClick={() => save(record.collegeAreaId)}>
                    保存
                </Tag>
                <Popconfirm title="确定取消吗?" onConfirm={cancel}>
                    <Tag className="tags-hover " color="#f50" icon={<CloseOutlined />}>取消</Tag>
                </Popconfirm>
            </>) : (
                <small onClick={e => e.stopPropagation()}>
                    <Popconfirm title="确定要删除？" onConfirm={e => {
                        deleteAddress.run({ collegeAreaId: record.collegeAreaId.toString() })
                        //TODO 后需要进行删除操作
                    }}>
                        <Tag className="tags-hover delete" color="#f50" icon={<DeleteOutlined />}>删除</Tag>
                    </Popconfirm>

                    <Tag className="tags-hover " color="#f50" icon={<EditOutlined />}
                        onClick={() => edit(record)}>编辑</Tag>
                </small>
            )
        }
    }
    ]

    const mergedColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: any) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });


    // const addressdata=[{AddressId:"1",campus:"清水河校区",ridgepole:"1",unit:"1",room:"301"}]
    //点击刷新按钮
    function onRefresh() {
        // getDept.run()
        getAddress.run()

    }

    //点击新增按钮
    function onAdd() {
        getCampus.run();
        setaddVisible(true)
    }

    function onColumnsChange(checkedList: any[]) {
        setcolumnsKey(checkedList)
    }


    //监听变化
    useEffect(() => {
        const realColumns = mergedColumns.filter(item => columnsKey.indexOf(item.key) !== -1)
        console.log(realColumns);

        setrealColumns(realColumns)
    }, [columnsKey])




    //得到校区下拉菜单
    async function getCampusSelect() {
        try {
            const json = await fetchRequest(url.GET_CAMPUS_SELECT, "");
            console.log("校区数据")
            console.log(json.data)
            if (json.success) {
                dispatch({
                    type: actionType.GET_COLLEGE_SELECT,
                    payload: json.data
                })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getCampus = useRequest(getCampusSelect, {
        manual: true,
        loadingDelay: 200
    })

    //得到地址
    async function getCampusTable() {
        try {
            const json = await fetchRequest(url.GET_CAMPUS_DETAIL, "");
            if (json.success) {
                dispatch({
                    type: actionType.GET_CAMPUS_TABLE,
                    payload: { data: json.data, count: json.count, total: json.total }
                })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getAddress = useRequest(getCampusTable, {
        manual: true,
        loadingDelay: 3000
    })

    //监听变化
    useEffect(() => {
        getAddress.run()
    }, [Info.rp])


    //删除地址的接口
    async function deleteAddressRequest(params: { collegeAreaId: any }) {
        console.log(params)
        try {
            const json = await fetchRequest(url.DELETE_CAMPUS, params);
            if (json.success) {
                message.destroy();
                message.success("删除成功！");
                getAddress.run()
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }


    const deleteAddress = useRequest(deleteAddressRequest, {
        manual: true,
        loadingDelay: 200
    })

    //点击分页的时候
    function handlePageChange(page: number) {
        dispatch({ type: actionType.SET_ADDRESS_PARAMS, payload: { index: page } })
    }

    //新增成功
    function addSuccess() {
        message.destroy();
        message.success("新增成功!");
        setaddVisible(false);
        getAddress.run()
    }

    return (
        <div>
            <Card className="search-form-table">
                <TableToolbar tableName="校区清单" columns={columns} TableSetting={false}
                    onColumnsChange={onColumnsChange} onRefresh={onRefresh} onAdd={onAdd} />
                <Form form={form} component={false}>
                    <Table

                        components={{
                            body: {
                                cell: EditableCell,
                            },
                        }}
                        pagination={{
                            total: addressInfo.campustable.total,
                            hideOnSinglePage: true,
                            simple: true,
                            onChange: handlePageChange,
                            current: addressInfo.requestAddressParams.index,
                            showSizeChanger: false
                        }}
                        rowKey={(record: any) => record.collegeAreaId} columns={mergedColumns}
                        loading={getAddress.loading}
                        dataSource={addressInfo.campustable.data}
                    />
                </Form>
                

            </Card>

    

            <Drawer width="60%" destroyOnClose visible={addVisible} title="新增校区信息" onClose={() => setaddVisible(false)}>
                <AddCampus addSuccess={addSuccess} />
            </Drawer>

        </div>
    )

}
